

####################################################
####          Replication Code for              ####
####     Spatial Interdependence                ####
####     and Instrumental Variable Models       ####
####################################################
####                                            ####
####                9/ 06/2018                  ####
####  this file creates Tables for              ####
####      the Ashraf- Galor Replication         ####
####               Appendix E                   ####
###                                             ####
####################################################



library(haven)
library(countrycode)
library(cshapes)
library(spdep)
library(plyr)



## load data
data = read_dta("20081371_Dataset.dta")
head(data)


### subset to where IV is available for 1000 CE
data_E2 = subset(data, cleanpdtech1000iv == 1)

#### use country code package to add cowcode
data_E2$COWCODE = countrycode(data_E2$code, "wb", "cown", warn = TRUE)
#### add romania cowcode since it wasn't matched
data_E2$COWCODE[data_E2$code == "ROM"] = 360

### use cshapes package to download world map for year 2000
cshp = cshp(date=as.Date(paste(2000,"-6-30", sep = "")), useGW=TRUE)

### subset to countries that are in cshapes
data_E2 = data_E2[data_E2$COWCODE %in% cshp$COWCODE,]
### subset cshapes to countries that are in our data
cshp = cshp[cshp$COWCODE %in% data_E2$COWCODE,]

### merge Ashraf and Galor data to shapefile
cshp@data = join(cshp@data, data_E2, by = "COWCODE", )

#### create neighbors
neighbors = poly2nb(cshp)

lw = nb2listw(neighbors, style="W", zero.policy=TRUE)
W = listw2mat(lw)

write.table(W, "W_E2.csv", sep=",", col.names=F, row.names=F)
cshp@data$id = seq(1:dim(cshp@data)[1])
write_dta(cshp@data, "AshrafGalor_data_E2.dta")




### data for IV in 1CE is available
data_E3 = subset(data, cleanpdtech1iv == 1)

data_E3$COWCODE = countrycode(data_E3$code, "wb", "cown", warn = TRUE)
data_E3$COWCODE[data_E3$code == "ROM"] = 360

cshp = cshp(date=as.Date(paste(2000,"-6-30", sep = "")), useGW=TRUE)
data_E3 = data_E3[data_E3$COWCODE %in% cshp$COWCODE,]
cshp = cshp[cshp$COWCODE %in% data_E3$COWCODE,]

cshp@data = join(cshp@data, data_E3, by = "COWCODE", )
                                        #k = knearneigh(coordinates(cshp), k =4, longlat = TRUE)

neighbors = poly2nb(cshp)#knn2nb(k)
lw = nb2listw(neighbors, style="W", zero.policy=TRUE)
W = listw2mat(lw)

write.table(W, "W_E3.csv", sep=",", col.names=F, row.names=F)
cshp@data$id = seq(1:dim(cshp@data)[1])
write_dta(cshp@data, "AshrafGalor_data_E3.dta")
